package controller.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.User;

public class Dao_User {
	EntityManager manager;
	
	public boolean save(User user) {
		try	{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();			
			manager.merge(user);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	public List<User> listAll(int inicio, int quant){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT u FROM User u where u.active = 1" );
		@SuppressWarnings("unchecked")
		List<User> users = query.setMaxResults(quant).setFirstResult(inicio).getResultList();
		manager.close();
		return users;
	}
	public boolean update(User user){
		try{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(user);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e){
			return false;
		}
	}
	public boolean delete(User user){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(user);
			manager.getTransaction().commit();
			manager.close();				
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	public User list(int id){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			User user = manager.find(User.class, id);
			manager.close();			
			return user;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
	public User log(String pass, String name){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			Query query = (Query) manager.createQuery("SELECT u FROM User u where u.login = :n and u.password = :p" );
			query.setParameter("n", name);
			query.setParameter("p", pass);
			User user = (User) query.getSingleResult();
			manager.close();
			if(user != null)
				return user;
			else
				return null;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
	public Long totalUser(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT count(u) FROM User u where u.active = 1" );
		Long total = (Long) query.getSingleResult();
		manager.close();
		return total;
	}
}